package com.geek.javase.ch18.work.work1;

import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

/*
 *@Date 2025/11/7
 *@Author wangpeng
 *@Description
 * * * 反射: “暴力破解”
 *  * 1.破坏封装性
 *  * 2.破坏泛型
 *  *
 *  * 需求：获取对象的所有属性及其值，以 name-张三 ，num-101 ， age=18存入obj.txt文件中
 *  * 格式如下：
 *     ----------Teacher+-----------
 *     name - 王朝
 *     workAge - 10
 *     major - 舞蹈
 *     ----------Student+-----------
 *     name - 张三
 *     num - 101
 *     age - 18
 */
public class ReflectObject {
    public static void main(String[] args) {
        Student student = new Student("张三", 101, 18);
        Teacher teacher = new Teacher("王朝", 10, "舞蹈");

        print(teacher, "obj.txt");
        print(student, "obj.txt");
    }

    public static void print(Object object, String fileName) {
        try (
                FileWriter fw = new FileWriter(fileName, true);
        ) {
            //获得类类型
            Class<?> clazz = object.getClass();
            fw.write("----------" + clazz.getSimpleName() + "+----------\n");
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                fw.write(field.getName() + " - " + field.get(object) + "\n");
            }
            fw.write("\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
